<?php namespace Manage;

use Illuminate\Validation\Validator;

class Device extends Base {

	protected $table = 'devices';

	/**
	 * 获取代理商设备指针
	 * @return [type] [description]
	 */
	static function getDeviceByAgent()
	{
		return \DB::table('agents_device')->where('agent_id', parent::getAgentId());
	}


	/**
	 * 获取代理商所有设备数据
	 * @param  int $id 代理商ID
	 * @return [type]     [description]
	 */
	static public function getAllDeviceData()
	{
		$deviceInfos = \DB::select('select ad.device_id, ad.sensor_id, ad.group_id, d.title, d.address from agents_device as ad, devices as d where ad.device_id = d.id && ad.sensor_id != 0 && ad.agent_id = ?;', array(parent::getAgentId()));
		
		if( empty($deviceInfos) )
		{
			return;
		}

		$sensorIds = array();
		foreach ($deviceInfos as $k => $val) 
		{
			if( empty($val->address) )
			{
				$val->address = '地址未填写';
			}
            $device_ids[]=$val->device_id;
			$sensorIds[$val->sensor_id] = $val;
		}



		//获取组信息
		$groupInfos = Group::getGroup(parent::getAgentId());

		//获取最新设备信息
		$sensorIdStr = implode(',', array_keys($sensorIds));


		$dataPoint = \DB::select('select sensor_id, `value` from (select sensor_id, `value` from data_points where sensor_id in(' . $sensorIdStr . ') order by `key` desc) as tb group by sensor_id');

		foreach ($dataPoint as $k => $v) 
		{
			$dataPoints[$v->sensor_id] = $v->value;
		}
        //获取电话
        $mobiles=\DB::table('member_device')
            ->join('members','member_device.member_id','=','members.id')
            ->whereIn('member_device.device_id',$device_ids)
            ->select('member_device.device_id as device_id','members.*')
            ->lists('device_id','username');
        $arr=array();
        if($mobiles){
            //显示绑定的所有电话
            foreach($mobiles as $k=>$m){
                $arr[$m]=isset($arr[$m])?$arr[$m].'<br/>'.$k:$k;//多个电话
            }
        }


		//数据处理
		$result = array();
		$result['group'] = $groupInfos;
		foreach ($sensorIds as $sensorId => $vals) 
		{
			$result['data'][$sensorId]['val'] = isset($dataPoints[$sensorId])?$dataPoints[$sensorId]:0;
			$result['data'][$sensorId]['title'] = $vals->title;
			$result['data'][$sensorId]['address'] = explode(';', $vals->address);
            $result['data'][$sensorId]['mobiles']=isset($arr[$vals->device_id])?$arr[$vals->device_id]:null;

			// if( empty( $groupId ) )
			// {
			// 	break;
			// }
			$result['data'][$sensorId]['groupName'] = isset($groupInfos[$vals->group_id])?$groupInfos[$vals->group_id]:'其他';
		}

		return $result;
	}

	/**
	 * 根据小区获取设备数据
	 * @param  [type] $gid [description]
	 * @return [type]      [description]
	 */
	static public function getDeviceByGroup($gid)
	{

        $page = $_ENV['PAGINATE'];
        $where = array();

        if ($gid !== 'all') {
            $where = array('group_id' => $gid);
        }

        //获取设备ID
        $deviceIds = \DB::table('agents_device')->where($where)->lists('device_id');

        //获取设备信息
        $devices = \DB::table('devices')->whereIn('id', $deviceIds)->select('id', 'title', 'communication_serial', 'hardware_serial', 'status as status_')->paginate($page);

        //获取设备对应用户ID
        $date = \DB::table('member_device')->join('members', 'members.id', '=', 'member_device.member_id')->whereIn('device_id', $deviceIds)
            ->select('member_device.device_id', 'member_device.member_id', 'members.username as mobile')
            ->get();

        //数据整理


        foreach ($devices as $key => $val) {
            //发放状态
            $status = '未发放';
            $number = null;

            foreach ($date as $k => $v) {


                if ($val->id == $v->device_id) {

                    $status = '已发放';
                    if (!$number) {
                        $number = $v->mobile;
                    } else {
                        $number = $number . ';' . $v->mobile;
                    }
                }
            }
            if (!$number) {
                $number = '未绑定';
            }
            switch ($val->status_) {
                case 0:$devices[$key]->status_ = '未知';break;
                case 1:$devices[$key]->status_ = '出厂';break;
                case 2:$devices[$key]->status_ = '服务中';break;
                case 3:$devices[$key]->status_ = '返修';break;
                case 4:$devices[$key]->status_ = '未激活';break;
            }

            $devices[$key]->status = $status;
            $devices[$key]->mobile = $number;
        }
        return $devices;
	}

	/**
	 * 设备绑定
	 * @param  [type] $uid   代理商ID
	 * @param  [type] $input 传入值
	 * @return [type]        [description]
	 */
	static public function bindDevice($uid, $input)
	{

        if(empty($input['group-n'])&&empty($input['name'])&&empty($input['location'])){
            return self::setErrorMsg('','请选择小区');
        }

        if(!$input['hardware_serial']){
            return self::setErrorMsg('','请填写硬件序列号');
        }
        if(!$input['address1']||!$input['address2']||!$input['address3']){
            return self::setErrorMsg('','请填写单元号');
        }
		$phones = array();

		//获取同时绑定数量
		foreach ( $input as $k => $name )
		{
			if( stristr( $k, 'phone' ) )
			{
				$phones[] = $name;
			}
		}

		//获取设备ID
		$deviceId = Device::where('hardware_serial', $input['hardware_serial'])->select('id')->get();

		//验证是否需要新建分组
		$gid = 0;

		if( isset($input['group-n']) && $input['group-n'] == 0 && !empty( $input['name'] ) )
		{
			$gid = Group::createGroup($uid, $input['name'], $input['location']);
		}
		else
		{
			$gid = $input['group-n'];
		}



       if(empty($deviceId[0])){

            return self::setErrorMsg('','硬件序列号有误');
       }

		Group::bindGroup($uid, $deviceId[0]->id, $gid);

		//记录设备信息
		$address = '';

		if( !empty($input['address1']) )
		{
			$address .= $input['address1'].';';
		}
		if( !empty($input['address2']) )
		{
			$address .= $input['address2'].';';
		}
		if( !empty($input['address3']) )
		{
			$address .= $input['address3'];
		}

		Device::where('hardware_serial', $input['hardware_serial'])->update(array('address' => $address));

		//设备绑定
		$res=Device::binds($phones, $input['hardware_serial']);
        if($res)
        {
            return self::setSuccessMsg('操作成功！');
        }else{
            return self::setErrorMsg('设备绑定失败！请检查网络！');
        }

	}


	/**
	 * 设备绑定操作
	 * @param  [type] $phones          [description]
	 * @param  [type] $hardware_serial [description]
	 * @return [type]                  [description]
	 */
	static public function binds($phones, $hardware_serial)
	{

		//数据写入
		foreach ($phones as $phone) 
		{
			$data = Base::socketPost($_ENV['API_URI']."user/binding_device", array('hardware_serial'=> $hardware_serial,'phone'=>$phone));

			 $jsonData = json_decode($data);
			//$jsonData = json_decode(trim(substr($data, 3, strlen($data) - 10)));


			if( intval( $jsonData->errcode ) != 0 )
			{
				return false;
			}

		}
        return true;

	}

	/**
	 * 回调获取注册用户数据(缺省)
	 * @param  [type] $val [description]
	 * @return [type]      [description]
	 */
	static public function getCallbackPhones($val)
	{

		if( stristr($val, 'phone') )
		{
			return true;
		}
		return false;

	}

	/**
	 * 获取设备信息
	 * @param  [type] $deviceId 设备ID
	 * @return [type]           [description]
	 */
	static public function getDeviceInfo($id)
	{
		if( empty( $id ) )
		{
			return false;
		}

		//获取设备基本信息
		$deviceInfo = Device::where('id', $id)->select('title', 'communication_serial', 'hardware_serial', 'about', 'address')->get();
		
		//获取设备绑定手机号信息
		$memberIds = \DB::table('member_device')->where('device_id', $id)->lists('member_id');

		$phoneNumbers = \DB::table('members')->whereIn('id', $memberIds)->orderBy('id', 'asc')->lists('username', 'id');

        //小区列表

		$deviceInfo[0]->phones = $phoneNumbers;
		$deviceInfo[0]->local = explode(';', $deviceInfo[0]->address);
        $deviceInfo[0]->area=self::getArea($id);
        $deviceInfo[0]->list=Group::getGroup();
		return $deviceInfo;
	}

	/**
	 * 根据其他信息获取设备表的设备ID
	 * @param  string $name 字段名
	 * @param  string $val 值
	 * @return int      设备ID
	 */
	static public function getDeviceIdByOther($name, $val)
	{
		return Device::where($name, $val)->pluck('id');
	}

	/**
	 * 验证是否为代理商所属设备
	 * @param  int $id 设备ID
	 * @return int      设备ID
	 */
	static public function checkDevice($id)
	{

		if( self::getAgent($id)->id==\Session::get('id'))
		{
			return false;
		}
		return true;

	}

	/**
	 * 获取所有未分组的代理商设备
	 * @param  int $id 设备ID
	 * @param  int $type 包含子设备(1.是 0.否)
	 * @return array      id=>name
	 */
	static public function getAllDeviceUngroup($id, $type)
	{
		//是否包含子设备
		if( $type == 1 )
		{
			$ungroupIds = self::getDeviceByAgent()->whereIn('group_id', array(0,$id))->lists('id');
		}
		else
		{
			$ungroupIds = self::getDeviceByAgent()->where('group_id', 0)->lists('id');
		}

		if( empty( $ungroupIds ) )
		{
			return false;
		}
		
		$groupNames = Device::whereIn('id', $ungroupIds)->lists('title');

		$data = array();

		foreach ($ungroupIds as $k => $val) 
		{
			$data[$val] = $groupNames[$k];
		}

		return $data;

	}

	/**
	 * 根据指定分组ID获取分组下代理商设备ID
	 * @param  int $id 分组ID
	 * @return int      设备ID
	 */
	static public function getAllDevicebyGroup($id)
	{

		$groupIds = self::getDeviceByAgent()->where('group_id', $id)->lists('device_id');

		return $groupIds;

	}


	/**
	 * 根据设备ID获取前M条设备数据
	 * @param  int $id 设备ID
	 * @param  int $count 数据数量
	 * @return array
	 */
	static public function getDataByDeviceId($id, $count = 10)
	{

		$data = \DB::table('data_points')->where('sensor_id', $id)->orderBy('key', 'desc')->limit($count)->select('key', 'value')->get();

		return $data;

	}

	/**
	 * 根据设备ID修改设备信息
	 * @param  int $id 设备ID
	 * @param  array $data 设备信息
	 * @return [type]     [description]
	 */
	static public function editInfoByDeviceId($id, $data)
	{
		$addressStr = '';

		for($i = 1; $i < 4; $i++)
		{
			$addressStr .= array_pull($data, 'address'.$i).';';
		}

		$data['address'] = substr($addressStr, 0, strlen($addressStr) - 1);

		return Device::where('id', $id)->update($data);
	}

	/**
	 * 根据设备ID修改设备绑定
	 * @param  int $id 设备ID
	 * @param  array $memIds 用户ID组
	 * @param  array $phones 绑定号码
	 * @return [type]     [description]
	 */
	static public function editBindByDeviceId($id, $memIds = array(), $phones = array(), $hardwareSerial = '')
	{
		//获取设备ID绑定设备信息
		$memberIds = \DB::table('member_device')->where('device_id', $id)->lists('member_id');


		//验证是否移除旧设备
		if( count($memberIds) != count($memIds) )
		{
			$removeIds = array_diff($memberIds, $memIds);

			\DB::table('members')->whereIn('id', $removeIds)->delete();
		}

		//获取新绑定号码
		if( !empty( $phones ) )
		{
			$newPhones = array_pull($phones, 'n');

			if( !empty($newPhones) )
			{
				Device::binds($newPhones, $hardwareSerial);
			}
		}

		//设备修改
		$editIds = array_intersect($memberIds, $memIds);

		//todo
		foreach( $editIds as $k => $tid )
		{
			$checkNum = \DB::table('members')->where('id', $tid)->where('username', $phones[$k])->count();
			if( !empty($checkNum) )
			{
				continue;
			}
			\DB::table('members')->where('id', $tid)->update(array('username' => $phones[$k]));
		}
	}

	/**
	 * 根据手机号获取设备ID
	 * @param  int $phone 手机号
	 * @return [type]     [description]
	 */
	static public function getDevIdByPhone($phone)
	{
		//获取用户ID
		$uid = \DB::table('members')->where('username', $phone)->pluck('id');

		if( empty($uid) )
		{
			return false;
		}

		//后返回设备ID
		return \DB::table('member_device')->where('member_id', $uid)->pluck('device_id');

	}



	/**
	 * 获取设备返修列表
	 * @param  [type] $timeData [description]
	 * @return [type]           [description]
	 */
	static public function getDevRepairData($timeData = '')
	{
		$page = $_ENV['PAGINATE'];

		$data = \DB::table('agents_device_repair');

		if( !empty($timeData) )
		{
			$data = $data->whereBetween('created_at', $timeData);
		}

		//获取返修列表
		return $data->where('agent_id', parent::getAgentId())->get();
	}
    /**
     * 设备获取设备的省 市 县 小区,返回地址数组 array()
     */
    static public function getArea($device_id)
    {
        $device=\DB::table('devices')->find($device_id);
        $order=\DB::table('agents_order')->find($device->agents_order_id);
        $agent=Agent::find($order->agent_id);
        $arr[0]=$agent->province;
        $arr[1]=$agent->city;

        $relative=\DB::table('agents_device')->where('device_id',$device_id)->first();

        $arr[2]=0;
        $arr[3]='';

        if($relative)
        {
            $group=Group::find($relative->group_id);
            $arr[2]=$group->location;
            $arr[3]=$group->id;

        }else{
            $arr[2]=0;
            $arr[3]='';
        }

        return $arr;
    }
    /**
     * 获取代理商
     */

    static public function getAgent($device_id)
    {
        $device=self::find($device_id);

        $agent_id=\DB::table('agents_order')->where('id',$device->agents_order_id)->first()->agent_id;

        return \DB::table('agents')->find($agent_id);
    }

}
